#include "videowin.h"
#include "ui_videowin.h"

VideoWin::VideoWin(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::VideoWin)
{
    ui->setupUi(this);
    sockaddr = new QUdpSocket(this);
    timer = new QTimer(this);
    timer->setInterval(VIDEO_FRAMES); // 最低 50
    timer->setSingleShot(false);

    DebugTimer = new QTimer(this);
    DebugTimer->setInterval(SCREENSHOT_INTERVAL);
    DebugTimer->setSingleShot(false);

    connect(timer,SIGNAL(timeout()),this,SLOT(timeOutSlot()));
    connect(DebugTimer,SIGNAL(timeout()),this,SLOT(DebugTimerOutSlot()));

    connect(sockaddr,SIGNAL(readyRead()),this,SLOT(SocketReayRead()));
    connect(ui->deBug_save_button,SIGNAL(clicked()),this,SLOT(ExceptionStorageSlot()));

    serverAddress= QHostAddress(UDP_SERVER_IP);  //指定udp 网关服务器 地址
    serverPort = UDP_SERVER_POST;                             //指定 udp 服务器 端口
    connect(ui->save_button,SIGNAL(clicked()),this,SLOT(ButtonSaveSlot()));
    connect(ui->play_button,SIGNAL(clicked()),this,SLOT(ButtonPlaySlot()));
    timerState = false;
    timer->stop();
    newOpenCvThread = new OpenCvThread(this);
    connect(this,SIGNAL(newDataSignal(QByteArray)),newOpenCvThread,SLOT(newDataSlot(QByteArray)));
    connect(newOpenCvThread,SIGNAL(newAiDataSignal()),this,SLOT(newAiDataSlot()));
    ScreenshotGre = 1000;
    ScreenshotRed = 1000;
    ui->spinBox_red->setValue(ScreenshotRed);
    ui->spinBox_gre->setValue(ScreenshotGre);
    newOpenCvThread->start();



    connect(ui->spinBox_red,SIGNAL(valueChanged(int)),this,SLOT(redChanges(int)));
    connect(ui->spinBox_gre,SIGNAL(valueChanged(int)),this,SLOT(greChanges(int)));
    ui->textBrowser->clear();


    connect(ui->pushButton_user_photo,SIGNAL(clicked()),this,SLOT(userPhotoSlot()));
    connect(ui->pushButton_abnormal_photo,SIGNAL(clicked()),this,SLOT(debugPhotoSlot()));
    connect(ui->pushButton_down,SIGNAL(clicked()),this,SLOT(nextPhotoSlot()));
    connect(ui->pushButton_up,SIGNAL(clicked()),this,SLOT(UpPhotoSlot()));
}

VideoWin::~VideoWin()
{
    delete ui;
}
QByteArray VideoWin::getData() const
{
    return Data;
}

void VideoWin::setData(const QByteArray &value)
{
    Data.clear();
    Data = value;
}


void VideoWin::timeOutSlot()
{
    if(QWidget::isVisible())
    {
        QByteArray data;
        data.append("get_stream");
        if (sockaddr->writeDatagram(data, serverAddress, serverPort) == -1){
            qDebug() << "UDP data ssend err :" << sockaddr -> errorString();
        }
        else{
            qDebug() << "1.UDP data send okk";
        }
    }
}

void VideoWin::SocketReayRead()
{  
    qDebug() << "2.recv file okk";
    Data.resize(sockaddr->pendingDatagramSize());
    sockaddr->readDatagram(Data.data(),Data.size(),&serverAddress,&serverPort);


    if(!Image.loadFromData(Data)){
        qDebug() << "loadFromData err";
    }
#if 0
    ui->label->clear();
    ui->label->setPixmap(Image);
#endif
    emit newDataSignal(Data);

}

void VideoWin::ButtonSaveSlot()
{
    // 堵塞操作 防止产生过多 timerout 信号 ，socket 存储过多东西 内存溢出

    DELAY_OPERATIO_start
            DEBUG_DELAY_OPERATIO_start
            if(UserFilePath.isEmpty())
    {
        // 定义初始化保存路径 保存
        QString FilePath = QFileDialog::getExistingDirectory(NULL, "选择文件夹", "/");
        if (!FilePath.isEmpty())
        {
            UserFilePath = FilePath;
            DEBUG_DELAY_OPERATIO_stop
                    DELAY_OPERATIO_stop
                    return;
        }
    }if(UserFilePath.isEmpty())
    {
        DEBUG_DELAY_OPERATIO_stop
                DELAY_OPERATIO_stop
                return;
    }
    if(Data.isEmpty())
    {
        QMessageBox::information(this,"information","先开启视频帧播放");
        DEBUG_DELAY_OPERATIO_stop
                DELAY_OPERATIO_stop
                return;
    }
    // 自动保存第一次的路径 名字为时间加 jpg
    QDateTime localTime = QDateTime::currentDateTime();
    QString localTimeString = localTime.toString("yyMMddhhmmss");
    QString newFilePAth = UserFilePath+"/"+"JPG-"+localTimeString+".jpg";
    ui->textBrowser->append(newFilePAth);
    if(Image.save(newFilePAth))
        QMessageBox::information(this,"information","已保存");
    else
        QMessageBox::information(this,"information","未保存");
    DEBUG_DELAY_OPERATIO_stop
            DELAY_OPERATIO_stop
}

void VideoWin::ButtonPlaySlot()
{
    if(timerState == false)
    {

        timer->start();
        timerState = true;
    }
    else
    {
        timer->stop();
        timerState = false;
    }
}

void VideoWin::newAiDataSlot()
{
    OpenCvImage = newOpenCvThread->getNewAiData();
    ui->label->clear();
    ui->label->setPixmap(OpenCvImage);
    qDebug() << "5.set openCvimage okk";
}

void VideoWin::DebugTimerOutSlot()
{
    DELAY_OPERATIO_start
            int RedCount = newOpenCvThread->getRedCount();
    int GreenCount = newOpenCvThread->getGreenCount();
    if(RedCount<ScreenshotRed&&GreenCount<ScreenshotGre)
    {
        DELAY_OPERATIO_stop
                return;
    }
    QDateTime localTime = QDateTime::currentDateTime();
    QString localTimeString = localTime.toString("yyMMddhhmmss");

    QString newFilePAth = UserFilePath+"/"+(GreenCount>RedCount?"Green":"Red")+"BUG-JPG-"+localTimeString+".jpg";
    if(OpenCvImage.save(newFilePAth)){
        qDebug() << "debug save okk";
    }
    ui->textBrowser->append(newFilePAth);
    int Green= newOpenCvThread->getGreenCount();
    int Red = newOpenCvThread->getRedCount();
    QString count = "Red "+ QString::number(Red)+"  "+"Green "+QString::number(Green);
    ui->textBrowser->append(count);
    DELAY_OPERATIO_stop
}

void VideoWin::ExceptionStorageSlot()
{
    DELAY_OPERATIO_start
            if(DebugUserFilePath.isEmpty())
    {
        QString FilePath = QFileDialog::getExistingDirectory(NULL, "选择异常存储文件夹", "/");
        if (!FilePath.isEmpty()) {
            DebugUserFilePath = FilePath;
            DELAY_OPERATIO_stop
                    return;
        }
    }
    if(DebugUserFilePath.isEmpty())
    {
        DELAY_OPERATIO_stop
                return;
    }
    if(OpenCvImage.isNull())
    {
        QMessageBox::information(this,"information","先开启视频帧播放");
        DELAY_OPERATIO_stop
                return;
    }





    if(DebugTimer->isActive())
    {
        DebugTimer->stop();
    }
    else
    {
        DebugTimer->start();
    }
    DELAY_OPERATIO_stop
}

void VideoWin::redChanges(int value)
{
    ScreenshotRed = value;
    ui->textBrowser->append("红色"+QString::number(ScreenshotRed)+"已添加");
}

void VideoWin::greChanges(int value)
{
    ScreenshotGre = value;
    ui->textBrowser->append("绿色"+QString::number(ScreenshotGre)+"已添加");
}

void VideoWin::userPhotoSlot()
{
    if(UserFilePath.isEmpty())
        {
            qDebug() << "请先选择文件目录";
            QMessageBox::information(this,"information","请先选择文件目录");
            return;
        }
        QDir dirPath;
        dirPath.setPath(UserFilePath);
        List = dirPath.entryList();
        qDebug() << List;
        List = List.filter(QRegExp("^JPG"));


        qDebug() << "";
        List.prepend("0");
        qDebug() <<List;
        albumState = 1;
}

void VideoWin::debugPhotoSlot()
{
    if(DebugUserFilePath.isEmpty())
        {
            qDebug() << "请先选择文件目录";
            QMessageBox::information(this,"information","请先选择文件目录");
            return;
        }
        QDir dirPath;
        dirPath.setPath(DebugUserFilePath);
        List = dirPath.entryList();
        qDebug() << List;

        List = List.filter(QRegExp("^BUG-JPG"));

        qDebug() << "";
        List.prepend("0");
        qDebug() <<List;
        albumState = 2;
}
void VideoWin::nextPhotoSlot()
{
    if(List.size()<=1)
    {
        qDebug() << "请先刷新相册";
        return;
    }
    int number = List.at(0).toInt();
    int size = List.size()-1 ;
    int newNumber = number+1>size?1:number+1;
    List[0] = QString::number(newNumber);
    qDebug() << newNumber;
    PhotoImage.load(((albumState == 1)?UserFilePath:DebugUserFilePath)+"\\"+List.at(newNumber));
    QSize PixmapSize = QSize(ui->label_Photo->width(),ui->label_Photo->height());
    PhotoImage = PhotoImage.scaled(PixmapSize,Qt::KeepAspectRatio,Qt::SmoothTransformation);
    ui->label_Photo->clear();
    ui->label_Photo->setPixmap(PhotoImage);
}

void VideoWin::UpPhotoSlot()
{
    if(List.size()<=1)
    {
        qDebug() << "请先刷新相册";
        return;
    }
    int number = List.at(0).toInt();
    int size = List.size()-1 ;
    int newNumber = number -1<=0?size:number-1;
    List[0] = QString::number(newNumber);
    qDebug() << newNumber;
    PhotoImage.load(((albumState == 1)?UserFilePath:DebugUserFilePath)+"\\"+List.at(newNumber));
    QSize PixmapSize = QSize(ui->label_Photo->width(),ui->label_Photo->height());
    PhotoImage = PhotoImage.scaled(PixmapSize,Qt::KeepAspectRatio,Qt::SmoothTransformation);
    ui->label_Photo->clear();
    ui->label_Photo->setPixmap(PhotoImage);
}

